﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Reflection;
using System.IO;
using System.Diagnostics;
using System.Text.RegularExpressions;

namespace template_dll
{
    public partial class ChildForm : Form
    {
        public ChildForm()
        {
            InitializeComponent();
        }

        private const string namechcol = "Флаг";
        private SqlConnection conn;
        private DataTable dt_rep;
        private delegate void Deleg();
        private Deleg del;
        private Guid guid;
        private CurrencyManager cm;
        private DataTable dt_citsup;
        private DataTable dt_enter;
        
        public static bool DisplayForm(System.Windows.Forms.Form theMDIParent)
        {
            ChildForm f = new ChildForm();
            f.MdiParent = theMDIParent;
            f.WindowState = FormWindowState.Maximized;
            f.Show();
            return true;
        }

        private string GetServ(string filename)
        {
            string str = "";
            using (StreamReader streamReader = new StreamReader(filename))
            {
                while (!streamReader.EndOfStream)
                {
                    str += streamReader.ReadLine();
                }
            }
            return str;
        }

        private void ChildForm_Load(object sender, EventArgs e)
        {
            conn = new SqlConnection(@"Server=" + GetServ("serv.txt") + ";Database=PharmOLAPDW;Integrated Security=True");
            dt_rep = new DataTable();
            dt_citsup = new DataTable();
            dt_enter = new DataTable();
            guid = Guid.NewGuid();
            DataGridViewRefresh();
            //DataGridViewSupplRefresh();
            //DataGridViewEnterRefresh();
            //CheckBoxIns();
        }

        private void CheckBoxIns()
        {
            foreach (DataGridViewColumn c in dataGridView1.Columns)
            {
                if (c.Name == "Код" || c.Name == "Аптека сокр" || c.Name == "Регион" || c.Name == "База МАП" ||
                    c.Name == "Открыта" || c.Name == "Дата открытия" || c.Name == "Дата закрытия" || c.Name == "Дата ребрендинга" ||
                    c.Name == "Область" || c.Name == "Город" || c.Name == "УРС" || c.Name == "Ответственный" ||
                    c.Name == "Кредит-нота" || c.Name == "Бренд")
                    c.Visible = true;
                else c.Visible = false;
            }
        }

        private void StartCreateRep(object sender, EventArgs e)
        {
            dataGridView1.DataSource = null;
            del = new Deleg(CreateRep);
            //this.Text += " Формируется";
            IAsyncResult asyncRes = del.BeginInvoke(new AsyncCallback(CallBackFunc), null); //
            panel1.Enabled = false;
            dataGridView1.Enabled = false;
        }

        private void CallBackFunc(IAsyncResult aRes)
        {
            del.EndInvoke(aRes);
            panel1.Invoke((Func<bool>)(() => panel1.Enabled = true));
            dataGridView1.Invoke((Func<bool>)(() => dataGridView1.Enabled = true));
            this.Invoke((Func<string>)(() => this.Text = this.Text.Replace(" Формируется", "")));
            dataGridView1.Invoke((Func<object>)(() => dataGridView1.DataSource = dt_rep.DefaultView));
        }

        private void CreateRep()
        {
/*            if (conn.State == ConnectionState.Closed) conn.Open();
            try
            {
                SqlCommand myCommand = conn.CreateCommand();
                myCommand.CommandType = CommandType.StoredProcedure;
                myCommand.CommandText = @"pas_GuidNatureCodeINS";
                myCommand.Parameters.Add("@guid", SqlDbType.UniqueIdentifier);
                myCommand.Parameters.Add("@code", SqlDbType.Int);
                myCommand.Parameters.Add("@del", SqlDbType.Bit);
                myCommand.Parameters.Add("@nature", SqlDbType.VarChar, 5);

                if (conn.State == ConnectionState.Closed) conn.Open();

                myCommand.Parameters["@guid"].Value = guid;
                myCommand.Parameters["@code"].Value = null;
                myCommand.Parameters["@del"].Value = true;
                myCommand.Parameters["@nature"].Value = null;
                myCommand.ExecuteNonQuery();

                guid = Guid.NewGuid();
                dt_rep.Load(RepProc(guid, conn));

                myCommand.Parameters["@guid"].Value = guid;
                myCommand.Parameters["@code"].Value = null;
                myCommand.Parameters["@del"].Value = true;
                myCommand.Parameters["@nature"].Value = null;
                myCommand.ExecuteNonQuery();

                conn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                conn.Close();
            }
            */
        }

        private SqlDataReader PharmViewSel(SqlConnection sqlcon,object param)
        {

            SqlCommand sqlcom = sqlcon.CreateCommand();
            sqlcom.CommandType = CommandType.StoredProcedure;
            sqlcom.CommandText = @"pas_PharmViewSel";
            sqlcom.CommandTimeout = 300;

            sqlcom.Parameters.Add("@pharmcode", SqlDbType.Int);
            sqlcom.Parameters["@pharmcode"].Value = param;

            if(sqlcon.State == ConnectionState.Closed) sqlcon.Open();
            return sqlcom.ExecuteReader();
        }

        private void ExpToExcel(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.FileName = "csv-file";
            sfd.Filter = "Файл CSV | *.csv";
            if (sfd.ShowDialog() == DialogResult.OK)
            {   
                SaveDGVToCSVfile(sfd.FileName.ToString(), dataGridView1, true);
            }
        }

        public static bool SaveDGVToCSVfile(string filename, DataGridView table, bool openInExcel)
        {
            try
            {
                StreamWriter sw = new StreamWriter(filename, false, Encoding.Unicode);

                List<int> col_n = new List<int>();
                foreach (DataGridViewColumn col in table.Columns)
                    if (col.Visible)
                    {
                        sw.Write(col.HeaderText + "\t");
                        col_n.Add(col.Index);
                    }
                sw.WriteLine();
                int x = table.RowCount;
                if (table.AllowUserToAddRows) x--;

                for (int i = 0; i < x; i++)
                {
                    for (int y = 0; y < col_n.Count; y++)
                        sw.Write(table[col_n[y], i].Value + "\t");
                    sw.Write(" \r\n");
                }
                sw.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return false;
            }

            if (openInExcel)
            {
                try
                {
                    Process newProc = Process.Start("excel.exe", "\"" + filename + "\"");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
            }
            return true;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DataGridViewRefresh();
        }

        private void DataGridViewRefresh()
        {
            try
            {
                dt_rep.Clear();
                dt_rep.Load(PharmViewSel(conn, DBNull.Value));
                dataGridView1.DataSource = dt_rep.DefaultView;
                cm = (CurrencyManager)dataGridView1.BindingContext[dataGridView1.DataSource];
                dataGridView1.Sort(dataGridView1.Columns[1], ListSortDirection.Ascending);
                conn.Close();
            }
            catch (Exception)
            {
                MessageBox.Show("Отсутствуют права на просмотр и редактирование данной страницы");
            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            Search(dataGridView1, textBox1);
        }

        private DataGridView Search(DataGridView dgv,TextBox tb)
        {
            cm.SuspendBinding();

            foreach (DataGridViewRow r in dgv.Rows)
            {
                dgv.Rows[r.Index].Visible = true;
                if (!Regex.Match(Convert.ToString(dgv[dgv.SortedColumn.Name, r.Index].Value), tb.Text, RegexOptions.IgnoreCase).Success)
                    r.Visible = false;
            }
            cm.ResumeBinding();
            return dgv;
        }

        private void dataGridView1_Sorted(object sender, EventArgs e)
        {
            Search(dataGridView1, textBox1);
        }

        private void dataGridView1_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {
            if (e.RowIndex > -1 && e.RowIndex < dataGridView1.RowCount - 1)
            {
                //cm.SuspendBinding();
                //
                dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = SystemColors.ControlLightLight;

                if (dataGridView1["База МАП", e.RowIndex].Value == DBNull.Value)
                    dataGridView1["База МАП", e.RowIndex].Style.BackColor = Color.Red;

                if (Convert.ToString(dataGridView1["Открыта", e.RowIndex].Value) == "нет")
                {
                    if (Convert.ToString(dataGridView1["Дата открытия", e.RowIndex].Value) == "")
                        dataGridView1["Дата открытия", e.RowIndex].Style.BackColor = Color.Red;
                    if (Convert.ToString(dataGridView1["Дата закрытия", e.RowIndex].Value) == "")
                        dataGridView1["Дата закрытия", e.RowIndex].Style.BackColor = Color.Red;
                }

                if (Convert.ToString(dataGridView1["Открыта", e.RowIndex].Value) == "да")
                {
                    if (Convert.ToString(dataGridView1["УРС", e.RowIndex].Value) == "")
                        dataGridView1["УРС", e.RowIndex].Style.BackColor = Color.Red;
                    if (Convert.ToString(dataGridView1["Регион", e.RowIndex].Value) == "")
                        dataGridView1["Регион", e.RowIndex].Style.BackColor = Color.Red;
                    if (Convert.ToString(dataGridView1["Область", e.RowIndex].Value) == "")
                        dataGridView1["Область", e.RowIndex].Style.BackColor = Color.Red;
                    if (Convert.ToString(dataGridView1["Город", e.RowIndex].Value) == "")
                        dataGridView1["Город", e.RowIndex].Style.BackColor = Color.Red;
                    if (Convert.ToString(dataGridView1["Ответственный", e.RowIndex].Value) == "")
                        dataGridView1["Ответственный", e.RowIndex].Style.BackColor = Color.Red;
                }
                //cm.ResumeBinding();
            }
        }

        private void dataGridView1_DoubleClick(object sender, EventArgs e)
        {
            Form2 f2 = new Form2();
            f2.pharmcode = Convert.ToInt32(dataGridView1["Код", dataGridView1.CurrentRow.Index].Value);
            f2.sqlconn = conn;
            f2.ShowDialog();
            f2.Close();
            f2 = null;

            DataGridViewRefresh();
            //CheckBoxIns();
            cm = (CurrencyManager)dataGridView1.BindingContext[dataGridView1.DataSource];
            dataGridView1.Sort(dataGridView1.Columns[1], ListSortDirection.Ascending);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            DataGridViewSupplRefresh();
        }

        private SqlDataReader PharmCitySuppSel(SqlConnection sqlcon, object param)
        {

            SqlCommand sqlcom = sqlcon.CreateCommand();
            sqlcom.CommandType = CommandType.StoredProcedure;
            sqlcom.CommandText = @"pas_PharmCitySupplSel";
            sqlcom.CommandTimeout = 300;

            //sqlcom.Parameters.Add("@pharmcode", SqlDbType.Int);
            //sqlcom.Parameters["@pharmcode"].Value = param;

            if (sqlcon.State == ConnectionState.Closed) sqlcon.Open();
            return sqlcom.ExecuteReader();
        }

        private void DataGridViewSupplRefresh()
        {
            try
            {
                dt_citsup.Clear();
                dt_citsup.Load(PharmCitySuppSel(conn, DBNull.Value));
                dataGridView2.DataSource = dt_citsup.DefaultView;
                cm = (CurrencyManager)dataGridView2.BindingContext[dataGridView2.DataSource];
                dataGridView2.Sort(dataGridView2.Columns[1], ListSortDirection.Ascending);
                conn.Close();
            }
            catch (Exception)
            {
                MessageBox.Show("Отсутствуют права на просмотр и редактирование данной страницы");
            }
        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            Search(dataGridView2, textBox2);
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (tabControl1.SelectedIndex == 0)
                {
                    DataGridViewRefresh();
                }
                if (tabControl1.SelectedIndex == 1)
                {
                    DataGridViewSupplRefresh();
                }
                //if (tabControl1.SelectedIndex == 2)
                //{
                //    DataGridViewEnterRefresh();
                //}
            }
            catch (Exception)
            {
                MessageBox.Show("У вас не хватает прав для просмотра этой вкладки");
            }
        }

        private void dataGridView2_Sorted(object sender, EventArgs e)
        {
            Search(dataGridView2, textBox2);
        }

        private void dataGridView2_DoubleClick(object sender, EventArgs e)
        {
            Form3 f3 = new Form3();
            f3.pharmcode = Convert.ToInt32(dataGridView2["Код аптеки", dataGridView2.CurrentRow.Index].Value);
            f3.sqlconn = conn;
            f3.ShowDialog();
            f3.Close();
            f3 = null;

            DataGridViewSupplRefresh();
            cm = (CurrencyManager)dataGridView2.BindingContext[dataGridView2.DataSource];
            dataGridView2.Sort(dataGridView2.Columns[1], ListSortDirection.Ascending);
        }

        private void button3_Click(object sender, EventArgs e)
        {
           
        }

        private SqlDataReader PharmCityEnterSel(SqlConnection sqlcon, object param)
        {

            SqlCommand sqlcom = sqlcon.CreateCommand();
            sqlcom.CommandType = CommandType.StoredProcedure;
            sqlcom.CommandText = @"CountDW..pas_PharmEnterSel";
            sqlcom.CommandTimeout = 300;

            if (sqlcon.State == ConnectionState.Closed) sqlcon.Open();
            return sqlcom.ExecuteReader();
        }

        private SqlCommand AddParam(SqlCommand c, DbType dt, string param, object val)
        {
            c.Parameters.AddWithValue(param, val);
            //c.Parameters[param].Value = val;
            return c;
        }
    }
}
